package com.teacherprofile.manage.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacherprofile.common.annotation.DataScope;
import com.teacherprofile.common.constant.BusinessConstants;
import com.teacherprofile.common.constant.RefresherTrainingsConstants;
import com.teacherprofile.common.core.domain.entity.SysUser;
import com.teacherprofile.common.enums.CheckStatus;
import com.teacherprofile.common.exception.ServiceException;
import com.teacherprofile.framework.manager.AsyncManager;
import com.teacherprofile.framework.manager.factory.AsyncFactory;
import com.teacherprofile.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.teacherprofile.manage.mapper.RefresherTrainingsMapper;
import com.teacherprofile.common.domain.RefresherTrainings;
import com.teacherprofile.manage.service.IRefresherTrainingsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.teacherprofile.common.constant.BusinessConstants.*;

/**
 * 进修培训Service业务层处理
 *
 * @author vibelin
 * @date 2025-05-16
 */
@Service
public class RefresherTrainingsServiceImpl extends ServiceImpl<RefresherTrainingsMapper, RefresherTrainings> implements IRefresherTrainingsService {
    @Autowired
    private RefresherTrainingsMapper refresherTrainingsMapper;
    @Autowired
    private ISysUserService userService;
    private final Map<Long, ReentrantLock> locks = new ConcurrentHashMap<>();

    /**
     * 获取细粒度锁对象
     *
     * @param id 业务id
     * @return
     */
    private ReentrantLock getLock(Long id) {
        locks.computeIfAbsent(id, k -> new ReentrantLock());
        return locks.get(id);
    }

    /**
     * 用于更新
     * 合法性校验 包括判空、幂等
     *
     * @param refresherTrainings
     */
    private void validCheck(RefresherTrainings refresherTrainings) {
        if (ObjectUtils.isNull(refresherTrainings)) {
            throw new ServiceException(BUSINESS_ERROR);
        }

        RefresherTrainings trainings = lambdaQuery()
                .eq(RefresherTrainings::getId, refresherTrainings.getId())
                .one();
        if (ObjectUtils.isEmpty(trainings)) { // 没有找到进修培训
            throw new ServiceException(BusinessConstants.BUSINESS_ERROR);
        }
        if (!trainings.getCheckStatus().equals(CheckStatus.WAITING_CHECK.getCode())) {
            // 如果状态不是待审核状态表示已经被处理过了
            throw new ServiceException(REPEAT_CONSUME_ERROR);
        }
    }

    private boolean myUpdate(RefresherTrainings refresherTrainings) {
        ReentrantLock lock = getLock(refresherTrainings.getId()); // 细粒度加锁
        // 查询当前id的进修培训
        if (lock.tryLock()) { // 尝试加锁
            try {
                validCheck(refresherTrainings);
                return updateById(refresherTrainings);
            } finally {
                lock.unlock();
            }
        }
        return false;
    }

    /**
     * 查询进修培训
     *
     * @param id 进修培训主键
     * @return 进修培训
     */
    @Override
    public RefresherTrainings selectRefresherTrainingsById(Long id) {
        return lambdaQuery().eq(RefresherTrainings::getId, id).one();
    }

    /**
     * 查询进修培训列表
     *
     * @param refresherTrainings 进修培训
     * @return 进修培训
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RefresherTrainings> selectRefresherTrainingsList(RefresherTrainings refresherTrainings) {
        return refresherTrainingsMapper.selectRefresherTrainingsList(refresherTrainings);
    }

    /**
     * 新增进修培训
     *
     * @param refresherTrainings 进修培训
     * @return 结果
     */
    @Override
    public boolean insertRefresherTrainings(RefresherTrainings refresherTrainings) {
        String userName = refresherTrainings.getUserName();
        if (ObjectUtils.isNull(userName)) {
            throw new ServiceException(EMPTY_USER_NAME_ERROR);
        }
        // 根据教职工号查询用户
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (ObjectUtils.isEmpty(sysUser)) {
            // 用户不存在
            throw new ServiceException(EMPTY_USER_ERROR);
        }
        // 用户存在，设置用户的userId与部门id，保存
        refresherTrainings.setUserId(sysUser.getUserId());
        refresherTrainings.setDeptId(sysUser.getDeptId());
        return save(refresherTrainings);
    }


    /**
     * 批量删除进修培训
     *
     * @param ids 需要删除的进修培训主键
     * @return 结果
     */
    @Override
    public boolean deleteByIds(Long[] ids) {

        return removeByIds(CollUtil.toList(ids));
    }

    /**
     * 导入数据
     *
     * @param refresherTrainings 进修培训
     * @return
     */
    @Override
    @Transactional
    public boolean importData(List<RefresherTrainings> refresherTrainings) {
        // 判断传入的列表是否为空
        if (CollectionUtils.isEmpty(refresherTrainings)) {
            throw new ServiceException(EMPTY_ERROR);
        }
        // 查询导入的教职工号去重集合
        Set<String> userNameList = refresherTrainings.stream().map(item ->
                item.getUserName()).collect(Collectors.toSet());
        // 根据去重集合查询对应的用户
        List<SysUser> userList = userService.selectUserByUserNames(userNameList);
        // 判断查询结果是否为空
        if (ObjectUtils.isEmpty(userList)) {
            throw new ServiceException(EMPTY_USER_ERROR);
        }
        // 将列表转成Map，key为教职工号，value为SysUser对象
        Map<String, SysUser> userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserName, item -> item));
        for (RefresherTrainings item : refresherTrainings) {
            // 填充用户的userId与deptId
            SysUser sysUser = userMap.get(item.getUserName());
            item.setUserId(sysUser.getUserId());
            item.setDeptId(sysUser.getDeptId());
        }
        // 批量保存数据
        return saveBatch(refresherTrainings);
    }

    /**
     * 修改进修培训
     *
     * @param refresherTrainings 进修培训
     * @return 结果
     */
    @Override
    public boolean updateRefresherTrainings(RefresherTrainings refresherTrainings) {
        return myUpdate(refresherTrainings);
    }

    /**
     * 审批
     *
     * @param refresherTrainings 工作荣誉
     * @return
     */
    @Override
    public boolean check(RefresherTrainings refresherTrainings) {

        myUpdate(refresherTrainings); // 自定义更新
        if (refresherTrainings.getCheckStatus().equals(CheckStatus.PASS.getCode())) {
            // 审核通过
            // 通知用户，审核通过
            AsyncManager.me().execute(AsyncFactory.sendPassMsgToOne(refresherTrainings.getUserName(), RefresherTrainingsConstants.CHECKED_PASS+"名称为："+refresherTrainings.getTrainingName()));
        } else {
            // 审核不通过
            AsyncManager.me().execute(AsyncFactory.sendRejectMsgToOne(refresherTrainings.getUserName(), RefresherTrainingsConstants.CHECKED_REJECT));
        }
        return true;
    }

}
